package com.wennn.top.web.user;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wennn.top.common.vo.IResult;
import com.wennn.top.core.mybatis.vo.BEntity;
import com.wennn.top.core.util.ErrorHelper;
import com.wennn.top.security.util.ContextUtil;
import com.wennn.top.shop.biz.user.entity.YxUserAddress;
import com.wennn.top.shop.biz.user.service.IYxUserAddressService;
import com.wennn.top.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @description: 地址管理
 * @author: wennn
 * @date: 7/6/20
 */

@Api(tags = "用户地址",description = "用户相关地址信息")
@RestController
@RequestMapping("/address")
public class AddressRest {

    @Autowired
    IYxUserAddressService iYxUserAddressService;

    @GetMapping("/get/{id}")
    @ApiOperation("通过id获取地址")
    public IResult getOne(@PathVariable("id") int id){
        YxUserAddress address = iYxUserAddressService.getById(id);
        return ErrorHelper.ifPresent(address);
    }

    @GetMapping("/listAddr")
    @ApiOperation("获取当前用户地址")
    public IResult listAddr(){
        LambdaUpdateWrapper<YxUserAddress> queryWrapper = Wrappers.lambdaUpdate(YxUserAddress.class);
        queryWrapper.eq(YxUserAddress::getUid, ContextUtil.getUid()).orderByAsc(BEntity::getId);
        List<YxUserAddress> list = iYxUserAddressService.list(queryWrapper);
        return IResult.ok(list);
    }

    @DeleteMapping("/del/{id}")
    @ApiOperation("删除用户地址")
    public IResult delete(@RequestBody List ids){
        return ErrorHelper.delete(iYxUserAddressService.removeByIds(ids));
    }


    @PutMapping("/saveOrUpdate")
    @ApiOperation("新增或者修改")
    public IResult saveOrUpdate(YxUserAddress address){

        if(Objects.isNull(address.getId())){
            address.setAddTime(DateUtil.nowIntTime());
        }
        address.setUid(ContextUtil.getUid());

        return ErrorHelper.save(iYxUserAddressService.saveOrUpdate(address)).andOk(result ->((IResult<Long>)result).data(address.getId()));
    }

    @PostMapping("/set/{id}")
    @ApiOperation("设置默认地址")
    public IResult setDefault(@PathVariable("id") int id){

        // 先修全部改非默认
        iYxUserAddressService.update(Wrappers.lambdaUpdate(YxUserAddress.class).set(YxUserAddress::getIsDefault,false)
                .eq(YxUserAddress::getUid,ContextUtil.getUid())
                .ne(BEntity::getId,id)
        );
        // 在针对默认的修改
        iYxUserAddressService.update(Wrappers.lambdaUpdate(YxUserAddress.class).set(YxUserAddress::getIsDefault,true)
                .eq(YxUserAddress::getUid,ContextUtil.getUid())
                .eq(BEntity::getId,id)
        );

        return IResult.ok(id);
    }
}
